package com.hctforgreen.greenservice;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.widget.Toast;

import com.hctforgreen.greenservice.utils.ThemeStoreUtil;
import com.umeng.analytics.MobclickAgent;

import java.io.File;

public class ParentActivity extends Activity{
	
	
	protected final String FINISH_EXAMINE_ACTIVITY_ACTION = "finish_examine_activity_action";

	protected FinshExamineActivityReceiver mFinishExamineActivityReceiver;
	private Context mContext;
	
	/**
	 * 销毁的Activity
	 */
//	private static Activity finishActivity = null;
	
	/**
	 * 定义是否需要右滑返回动作
	 */
	protected boolean rightScroll = true;
	//手指上下滑动时的最小速度
    private static final int YSPEED_MIN = 1000;

    //手指向右滑动时的最小距离
    private static final int XDISTANCE_MIN = 130;

    //手指向上滑或下滑时的最小距离
    private static final int YDISTANCE_MIN = 100;

    //记录手指按下时的横坐标。
    private float xDown;

    //记录手指按下时的纵坐标。
    private float yDown;

    //记录手指移动时的横坐标。
    private float xMove;

    //记录手指移动时的纵坐标。
    private float yMove;

    //用于计算手指滑动的速度。
    private VelocityTracker mVelocityTracker;


	private long mLExitTime = 0;
	//判定双击的时间间隔
	private static final long mLDelayTime = 2000;
    
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mContext = this;
		super.onCreate(savedInstanceState);

		/*if(!rightScroll){
			finishActivity = null;
		}*/
		Log.d("温馨提示", "你现在看到的activity是："+getClass().getSimpleName());
	}
	/**
	 * @
	 * 初始化皮肤布局
	 * 
	 */
	protected void initSkinLayout() {
		try {
			View parentLyt = findViewById(R.id.lyt_parent);
			int skinId = ThemeStoreUtil.getSkinId(this);
			if (skinId != -1) {
				parentLyt.setBackgroundResource(skinId);
			} else {// skinId = -1  ---自定义背景
				String filePath = ThemeStoreUtil.getSkinFilePath(this);
				if (!TextUtils.isEmpty(filePath) && new File(filePath).exists()) {
					try {
						Drawable bitmapDrawable = new BitmapDrawable(
								getResources(), filePath);
						// DecodeBitmapUtil bitmapUtil = new DecodeBitmapUtil();
						parentLyt.setBackgroundDrawable(bitmapDrawable);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					parentLyt
							.setBackgroundResource(R.drawable.ic_default_activity_bg);
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	@Override
	protected void onPause() {
		MobclickAgent.onPause(mContext);
		super.onPause();
	}

	@Override
	protected void onResume() {
		MobclickAgent.onResume(mContext);
		super.onResume();
	}

	public class FinshExamineActivityReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			finish();
		}

	}

	protected void initFinshExamineActivityReceiver() {
		mFinishExamineActivityReceiver = new FinshExamineActivityReceiver();
		IntentFilter filter = new IntentFilter(FINISH_EXAMINE_ACTIVITY_ACTION);
		registerReceiver(mFinishExamineActivityReceiver, filter);
	}

	@Override
	protected void onDestroy() {
		if (mFinishExamineActivityReceiver != null) {
			unregisterReceiver(mFinishExamineActivityReceiver);
		}
		super.onDestroy();
	}

	//双击退出应用 20161205 390697
	public void doubleTouchExit(Context context) {
		if ((System.currentTimeMillis() - mLExitTime) > mLDelayTime) {
			Toast.makeText(
					context,
					getString(R.string.double_touch_exit_title)
							+ getString(R.string.app_name), Toast.LENGTH_SHORT)
					.show();
			mLExitTime = System.currentTimeMillis();
		} else {
			finish();
			System.exit(0);
		}
	}
	/**
	 * 重写滑动事件
	 * 增加右滑返回
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent event){
		if(this.rightScroll){
			createVelocityTracker(event);
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				xDown = event.getRawX();
				yDown = event.getRawY();
				break;
			case MotionEvent.ACTION_MOVE:
				xMove = event.getRawX();
				yMove= event.getRawY();
				//滑动的距离
				int distanceX = (int) (xMove - xDown);
				int distanceY= (int) (yMove - yDown);
				//获取顺时速度
				int ySpeed = getScrollVelocity();
				//关闭Activity需满足以下条件：
				//1.x轴滑动的距离>XDISTANCE_MIN
				//2.y轴滑动的距离在YDISTANCE_MIN范围内
				//3.y轴上（即上下滑动的速度）<XSPEED_MIN，如果大于，则认为用户意图是在上下滑动而非左滑结束Activity
				if(distanceX > XDISTANCE_MIN &&(distanceY<YDISTANCE_MIN&&distanceY>-YDISTANCE_MIN)&& ySpeed < YSPEED_MIN) {//右滑
					finish();
				}
				if(distanceX < -XDISTANCE_MIN &&(distanceY<YDISTANCE_MIN&&distanceY>-YDISTANCE_MIN)&& ySpeed < YSPEED_MIN) {//左滑
//					if(finishActivity != null){
//						final Intent intent = new Intent(mContext, finishActivity.getClass());
//						startActivity(intent);
//					}
					
				}
				
				break;
			case MotionEvent.ACTION_UP:
				recycleVelocityTracker();
				break;
			default:
				break;
			}
		}
		return super.dispatchTouchEvent(event);
		
	}
	 /**
     * 创建VelocityTracker对象，并将触摸界面的滑动事件加入到VelocityTracker当中。
     *
     * @param event
     *
     */
   private void createVelocityTracker(MotionEvent event) {
        if (mVelocityTracker == null) {
               mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(event);
   }

   /**
     * 回收VelocityTracker对象。
     */
   private void recycleVelocityTracker() {
         mVelocityTracker.recycle();
         mVelocityTracker = null;
   }

   /**
     *
     * @return 滑动速度，以每秒钟移动了多少像素值为单位。
     */
   private int getScrollVelocity() {
         mVelocityTracker.computeCurrentVelocity(1000);
         int velocity = (int) mVelocityTracker.getYVelocity();
         return Math.abs(velocity);
   }
   
  
   
}
